from datetime import datetime, timedelta
from jose import JWTError, jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from novelapp.models.models import User
# import logging
from novelapp.common.common import returnData,setLog

SECRET_KEY = "sudokuuuuaaa"  # 你应该使用更安全的方式保存这个密钥
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30000

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)

logger = setLog('noveapp.log')

def create_access_token(data: dict, expires_delta: timedelta = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt



async def get_user(token: str = Depends(oauth2_scheme)):
    # logger.error('111')
    
    # logger.error(f"111: {token}")
    
    if token is None:
        # logger.error('222')
        return None  # 如果没有提供 token，返回 None

    try:
        # logger.error(f"Unexpected error1: {token}")
        
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        openid = payload.get("sub")
        # logger.error(f"Unexpected error2: {openid}")
        if openid is None:
            return None  # 没有 sub claim，返回 None

        # 假设 User 是一个 ORM 模型，用于从数据库中获取用户
        user = User.objects.get(openid=openid)
        if user is None:
            return None  # 用户未找到，返回 None

        return user
    except JWTError as e:
        logger.error(f"JWT error: {e}")
        return None  # JWT 验证失败，返回 None
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        return None  # 其他错误，返回 None

def get_user_bak(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        print(payload)
        openid = payload.get("sub")
        if openid is None:
            
            return None  # 没有 sub claim，返回 None
            # raise HTTPException(
            #     status_code=status.HTTP_401_UNAUTHORIZED,
            #     detail="Missing sub claim in token",
            #     headers={"WWW-Authenticate": "Bearer"},
            # )

        # 假设 User 是一个 ORM 模型，用于从数据库中获取用户
        user = User.objects.get(openid=openid)
        if user is None:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="User not found",
                headers={"WWW-Authenticate": "Bearer"},
            )

        return user
    except JWTError as e:
        logger.info(f"JWT error: {e}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    except Exception as e:
        logger.info(f"Unexpected error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error",
        )